package com.briup.product_source.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.briup.product_source.dao.ManagerAnimalMapper;
import com.briup.product_source.dao.ManagerBatchMapper;
import com.briup.product_source.dao.ManagerHurdlesMapper;
import com.briup.product_source.dao.ManagerQrcodeMapper;
import com.briup.product_source.dao.ext.ManagerAnimalExtMapper;
import com.briup.product_source.exception.ServiceException;
import com.briup.product_source.pojo.ManagerAnimal;
import com.briup.product_source.pojo.ManagerBatch;
import com.briup.product_source.pojo.ManagerHurdles;
import com.briup.product_source.pojo.ManagerQrcode;
import com.briup.product_source.pojo.ext.ManagerAnimalExt;
import com.briup.product_source.result.ResultCode;
import com.briup.product_source.service.ManagerAnimalService;
import com.briup.product_source.util.JsonConverter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;



@Service
public class ManagerAnimalServiceImpl implements ManagerAnimalService {

    @Autowired
    private ManagerAnimalExtMapper managerAnimalExtMapper;
    @Autowired
    private ManagerAnimalMapper managerAnimalMapper;

    @Autowired
    private ManagerBatchMapper managerBatchMapper;

    @Autowired
    private ManagerHurdlesMapper managerHurdlesMapper;

    @Autowired
    private ManagerQrcodeMapper managerQrcodeMapper;

    @Override
    public PageInfo<ManagerAnimalExt> queryAndPage(Integer pageNum, Integer pageSize,
                                                   String aGender, String aHealthy) {
        PageHelper.startPage(pageNum,pageSize);
        List<ManagerAnimalExt> list  = managerAnimalExtMapper.queryAndPage(aGender,aHealthy,aGender,aHealthy);
        PageInfo<ManagerAnimalExt> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    @Transactional
    @Override
    public void saveOrUpdate(ManagerAnimal animal) {
        String bId = animal.getABatchId(); // 批次编号
        String hId = animal.getAHurdlesId(); // 栏圈编号
        // 参数校验
        if (!StringUtils.hasText(animal.getAWeight()) ||
                !StringUtils.hasText(animal.getAGender()) ||
                !StringUtils.hasText(animal.getAHealthy()) ||
                !StringUtils.hasText(animal.getAInoculate()) ||
                !StringUtils.hasText(bId) ||
                !StringUtils.hasText(hId) ||
                animal.getATime() == null) {
            throw new ServiceException(ResultCode.PARAM_IS_EMPTY);
        }
        ManagerHurdles hurdlesNew = managerHurdlesMapper.selectById(hId);
        Integer max = hurdlesNew.getHMax();
        Integer haveSaved = hurdlesNew.getHSaved();
        String status = hurdlesNew.getHFull();
        String aId = animal.getAAnimalId();
        if(aId == null){
            //进行新增
            ManagerBatch mb = managerBatchMapper.selectById(bId);
            if ("已检疫".equals(mb.getBQuarantine())) {
                animal.setAStatus("已检疫");
            }else {
                animal.setAStatus("养殖中");
            }
            animal.setAAnimalId(UUID.randomUUID().toString().replace("-",""));
            int result = managerAnimalMapper.insert(animal);
            if (result == 0) {
                // 添加失败
                throw new ServiceException(ResultCode.FAIL);
            }
            hurdlesNew.setHSaved(haveSaved + 1);
            if((haveSaved + 1) == max){
                hurdlesNew.setHFull("已满");
            }
            if (managerHurdlesMapper.updateById(hurdlesNew) == 0) {
                throw new ServiceException(ResultCode.FAIL);
            };
        }else{
            //进行修改操作
            ManagerAnimal ma = managerAnimalMapper.selectByPrimaryKey(aId);
            if(ma == null){
                throw new ServiceException(ResultCode.DATA_IS_EMPTY);
            }
            int result = managerAnimalMapper.updateByPrimaryKey(animal);
            if(result == 0)
                throw new ServiceException(ResultCode.FAIL);
            String hurdlesIdOld = ma.getAHurdlesId();
            ManagerHurdles hurdlesOld = managerHurdlesMapper.selectById(hurdlesIdOld);
            if(!hurdlesNew.equals(hurdlesIdOld)){
                hurdlesNew.setHSaved(haveSaved + 1);
                System.out.println();System.out.println();System.out.println();System.out.println();System.out.println();System.out.println();
                System.out.println(hurdlesNew);
                System.out.println();System.out.println();System.out.println();System.out.println();System.out.println();
                if ((haveSaved + 1) == max){
                    hurdlesNew.setHFull("已满");
                }
                if (managerHurdlesMapper.updateById(hurdlesNew) == 0) {
                    throw new ServiceException(ResultCode.FAIL);
                }
                hurdlesOld.setHSaved((hurdlesOld.getHSaved() - 1));
                if ("已满".equals(hurdlesOld.getHFull())) {
                    hurdlesOld.setHFull("未满");
                }
                if(managerHurdlesMapper.updateById(hurdlesOld) == 0)
                    throw new ServiceException(ResultCode.FAIL);
            }
        }
    }

    @Override
    public void deleteById(String id) {
        ManagerAnimal ma = managerAnimalMapper.selectByPrimaryKey(id);
        if(ma == null){
            throw new ServiceException(ResultCode.DATA_IS_EMPTY);
        }else {
            if(ma.getAStatus().equals("已销售")){
                ManagerHurdles mh = managerHurdlesMapper.selectById(ma.getAHurdlesId());
                if(managerAnimalMapper.deleteById(id) == 0){
                    throw new ServiceException(ResultCode.FAIL);
                }else {
                    if(mh.getHFull().equals("已满")){
                        mh.setHFull("未满");
                    }
                    mh.setHSaved(mh.getHSaved() - 1);
                    if(managerHurdlesMapper.updateById(mh) == 0)
                        throw new ServiceException(ResultCode.FAIL);
                }
            }else{
                throw new ServiceException(ResultCode.DATA_CAN_NOT_DELETE);
            }
        }
    }


    @Override
    public void deleteByIdAll(List<String> ids) {
        int rel = 0;
        int empty = 0;
        List<String> list = new ArrayList<>();
        for(String id : ids){
            ManagerAnimal ma = managerAnimalMapper.selectByPrimaryKey(id);
            if(ma == null){
                empty ++;
            }else {
                if(ma.getAStatus().equals("已销售")){
                    ManagerHurdles mh = managerHurdlesMapper.selectById(ma.getAHurdlesId());
                    list.add(id);
                    } else{
                    rel ++;
                }
            }
        }
        if(rel == ids.size())
            throw new ServiceException(ResultCode.DATA_CAN_NOT_DELETE);
        else if (empty == ids.size())
            throw new ServiceException(ResultCode.DATA_IS_EMPTY);
        else{
            int count = 0;
            int count2 = 0;
            for(String id : list){
                if(managerAnimalMapper.deleteById(id) == 0)
                    count ++;
                ManagerAnimal ma = managerAnimalMapper.selectByPrimaryKey(id);
                ManagerHurdles mh = managerHurdlesMapper.selectById(ma.getAHurdlesId());
                if(mh.getHFull().equals("已满")){
                    mh.setHFull("未满");
                }
                mh.setHSaved(mh.getHSaved() - 1);
                if(managerHurdlesMapper.updateById(mh) == 0)
                    count2 ++;
                if(count != count2){
                    throw new ServiceException(ResultCode.FAIL);
                }else{
                    break;
                }
            }
        }
    }


    @Override
    public void qRCode(String animalId) {
        int result;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ManagerAnimal animal = managerAnimalMapper.selectByPrimaryKey(animalId);
        String content;
        content = "http://192.168.42.1:9527/code" + "?animalId=" + animalId;
        QrCodeUtil.generate(content, 300, 300, "png",
                byteArrayOutputStream);
        byte[] qrCodeData = byteArrayOutputStream.toByteArray();

        // 指定保存二维码图片的文件路径
//        URL path = this.getClass().getClassLoader().getResource("qrcode");
//        File qrCodeFile = new File(path + "/" + animalId + ".jpg");
        File qrCodeFile = new File("C:\\Users\\Administrator\\Desktop\\qrcode\\" + animalId + ".jpg");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(qrCodeFile);
            fileOutputStream.write(qrCodeData);
            fileOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ManagerQrcode mq = managerQrcodeMapper.selectByaId(animalId);
        String truePath =  "http://localhost:9999/qrcode/" + animalId + ".jpg";
        if(mq == null){
            result =  managerQrcodeMapper.insert(animalId,truePath);
        }else {
            result = managerQrcodeMapper.update(animalId,truePath);
        }
        if(result == 0)
            throw new ServiceException(ResultCode.FAIL);

    }
}
